export class BlackBoardBg {
    public ctx!: CanvasRenderingContext2D; // 画板背景的上下文
    public width: number = 0; // 画板背景层的宽度
    public height: number = 0; // 画板背景层的高度

    public bgColor: string = '#ffffff'; // 画板的背景色
    public bgImage: string = ''; // 画板的背景图片

    constructor(public el: HTMLCanvasElement) {
        this.initCanvas();
    }

    // 画布的初始化
    initCanvas = () => {
        this.ctx = this.el.getContext("2d")!;
        const { width, height } = this.el.getBoundingClientRect();
        this.width = width;
        this.height = height;
        this.el.width = this.width;
        this.el.height = this.height;
        this.setBgColor(this.bgColor);
    }

    // 清空画布
    clearCanvas = (top = 0, left = 0, width = this.width, height = this.height) => this.ctx.clearRect(top, left, width, height);

    // 设置背景颜色
    setBgColor = (bgColor: string) => {
        this.clearCanvas()
        this.ctx.fillStyle = bgColor;
        this.ctx.rect(0, 0, this.width, this.height);
        this.ctx.fill();
    }

    // 设置背景图片
    setBgImage = (image: string) => {
        this.clearCanvas()
        this.bgImage = image;
        const img = new Image();
        img.src = image as string;
        img.onload = () => {
            this.clearCanvas()
            this.ctx.drawImage(img, 0, 0, this.width, this.height)
        }
    }
}